﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;

public partial class AccountsViewEN : System.Web.UI.Page
{

    public List<Persons> lstGridPersons
    {
        get
        {
            if (ViewState["lstGridPersons"] == null)
            {
                ViewState["lstGridPersons"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstGridPersons"].ToString()] == null)
            {
                Session[ViewState["lstGridPersons"].ToString()] = new List<Persons>();

            }

            return (List<Persons>)Session[ViewState["lstGridPersons"].ToString()];

        }
        set
        {
            if (ViewState["lstGridPersons"] == null)
            {
                ViewState["lstGridPersons"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstGridPersons"].ToString()] = value;
        }  



    }



    protected void Page_Load(object sender, EventArgs e)
    {
        Persons objPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objPersons);
       
        if (!Page.IsPostBack)
        {
            bindGrid("");
        }

    }



    /// <summary>
    /// this function will bind the grid with the persons
    /// </summary>
    protected void bindGrid(string strIn)
    {
        

        List<Persons> lstPersons = search(strIn);

        lstGridPersons = lstPersons;
        grdUsers.DataSource = lstPersons;
        grdUsers.DataBind();

        dvAllCount.InnerHtml = "Users Count : " + Persons.MyCount;

    }



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check



        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Acounts_page))
            Response.Redirect("LoginEN.aspx");




    }
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        bindGrid(txtSearch.Text);
    }




    /// <summary>
    /// this function will search in Persons and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of Persons  matched</returns>
    public static  List<Persons> search(string txtText)
    {
        
        PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);
        List<Persons> lstRet = new List<Persons>();
        
        if (txtText.Trim() == "")
        {
            List<Persons> lstNew = objPersonsDB.Select(" top 100 ", " order by [Name_EN] ");
            //lstNew = new List<Persons>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            return lstNew;
        }


        Persons objSearchPersons = new Persons();

        objSearchPersons.Badge = objSearchPersons.Name_AR = objSearchPersons.Name_EN = objSearchPersons.MiddleName_AR = objSearchPersons.MiddleName_EN = objSearchPersons.FamilyName_AR = objSearchPersons.FamilyName_EN = "%" + txtText + "%";

        lstRet = objPersonsDB.SearchOrLike(objSearchPersons);

        return lstRet;


        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }
        


        foreach (string strValue in strValues)
        {
            Persons objPersons = new Persons();
            objPersons.Badge = objPersons.ID = objPersons.FamilyName_AR = objPersons.FamilyName_EN = objPersons.Name_AR = objPersons.Name_EN =
                objPersons.MiddleName_AR = objPersons.MiddleName_EN = "%" + strValue + "%";

            List<Persons> lstPersons = objPersonsDB.SearchLikeOROrderByNAME_EN (objPersons);
            //lstPersons = new List<Persons>(from objFol in lstPersons where objFol.StatusID != 2 select objFol);

            foreach (Persons objFol in lstPersons)
            {
                if ((from objIn in lstRet where objIn.GenID == objFol.GenID select objIn).ToList().Count == 0)
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }




    


    protected void grdUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);


        //security
        if (!objCurrentPersons.lstAllRulesIDs.Contains((long)RulesEnum.Editing_Acounts_page))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }



        PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);


        List<Persons> lstPersons = objPersonsDB.getPersonsByGenID(long.Parse(grdUsers.DataKeys[e.RowIndex]["GenID"].ToString()));
        if (lstPersons.Count == 0)
        {
            lblError.Text = "No user to delete";
            lblResult.Text = "";
            return;
        }


       
            if ((from obj in lstPersons[0].lstGroups where obj.GroupNameEN == "Administrator" select obj).ToList().Count > 0)
            {
                if ((from obj in objCurrentPersons.lstGroups where obj.GroupNameEN == "Administrator" select obj).ToList().Count == 0)
                {
                    lblError.Text = "No previlige to delete that user";
                    lblResult.Text = "";
                    return;
                }
            }
        


      

        bool bRet = objPersonsDB.deleteAll(lstPersons[0]);






        if (!bRet)
        {
            lblError.Text = "Error deleting user";

        }
        else
        {
            bindGrid(txtSearch.Text);
        }



    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("AccountsEN.aspx");
    }
    
    
    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstGridPersons;
        grdUsers.PageIndex = e.NewPageIndex;
        grdUsers.DataBind();

    }


    /// <summary>
    /// this function will get the responsibility code
    /// </summary>
    /// <param name="dataItem">the person</param>
    /// <returns>responsibility code</returns>
    protected string getResponsibilityCode(object dataItem)
    {
        Persons objSelectedPersons = (Persons)dataItem;

        if (objSelectedPersons.objOrgnizationChart.ID <= 0)
            return "N/A";

        if (objSelectedPersons.objOrgnizationChart.OrgCode == "")
            return "N/A";


        return objSelectedPersons.objOrgnizationChart.OrgCode;

    }
}
